<template>
  <div class="profile-page">
    <header class="header">
      <h1>个人中心</h1>
      <div class="user-nav">
        <button @click="disconnectWallet" class="btn btn-disconnect" v-if="walletConnected">
          <i class="fas fa-sign-out-alt"></i> 断开钱包
        </button>
        <button class="btn btn-back" @click="goHome">
          <i class="fas fa-home"></i> 返回首页
        </button>
      </div>
    </header>

    <div class="wallet-info" v-if="walletConnected">
      <div class="wallet-avatar">
        <img :src="walletAvatar" alt="钱包图标" />
        <div class="wallet-status">
          <span class="status-indicator connected"></span>
          <span class="status-text">{{ walletConnected ? "已连接" : "未连接" }} · {{ currentWallet }}</span>
        </div>
      </div>
      
      <div class="wallet-details">
        <div class="wallet-address">
          <span>{{ shortenAddress(walletAddress) }}</span>
          <button @click="copyAddress" class="copy-button" title="复制地址">
            <i class="fas fa-copy"></i>
          </button>
          <span class="copy-feedback" v-if="showCopiedFeedback">已复制!</span>
        </div>
        <div class="wallet-balance">
          <span>ETH 余额: {{ ethBalance }} ETH</span>
          <button @click="refreshBalance" class="refresh-button" title="刷新余额">
            <i class="fas fa-sync-alt" :class="{ 'fa-spin': refreshingBalance }"></i>
          </button>
        </div>
      </div>
    </div>
    
    <div v-else class="connect-wallet">
      <button @click="connectMetaMask" class="btn btn-metamask" :disabled="connecting">
        <i class="fab fa-ethereum"></i> 
        <span v-if="!connecting">连接MetaMask</span>
        <span v-else>连接中...</span>
      </button>

      <button @click="connectGanache" class="btn btn-ganache" :disabled="connecting">
        <i class="fas fa-network-wired"></i> 
        <span v-if="!connecting">连接Ganache</span>
        <span v-else>连接中...</span>
      </button>
      
      <div class="wallet-tips" v-if="!walletConnected">
        <p><i class="fas fa-info-circle"></i> 请连接钱包以查看捐赠记录和个人信息</p>
      </div>
    </div>
    
    <div class="donation-history" v-if="walletConnected">
      <div class="section-header">
        <h2>我的捐赠记录</h2>
        <button @click="refreshDonations" class="btn btn-refresh" :disabled="refreshingDonations">
          <i class="fas fa-sync-alt" :class="{ 'fa-spin': refreshingDonations }"></i>
          {{ refreshingDonations ? '刷新中...' : '刷新记录' }}
        </button>
      </div>
      
      <div class="history-table" v-if="donations.length > 0">
        <table>
          <thead>
            <tr>
              <th @click="sortDonations('date')">
                日期 <i class="fas fa-sort" :class="{
                  'fa-sort-up': sortBy === 'date' && sortAsc,
                  'fa-sort-down': sortBy === 'date' && !sortAsc
                }"></i>
              </th>
              <th @click="sortDonations('amount')">
                捐赠金额 <i class="fas fa-sort" :class="{
                  'fa-sort-up': sortBy === 'amount' && sortAsc,
                  'fa-sort-down': sortBy === 'amount' && !sortAsc
                }"></i>
              </th>
              <th>捐赠项目</th>
              <th>状态</th>
              <th>交易哈希</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(donation, index) in donations" :key="index">
              <td>{{ formatDateTime(donation.date) }}</td>
              <td>{{ donation.amount }} ETH</td>
              <td>{{ donation.project }}</td>
              <td>
                <span :class="`status-${donation.status}`">
                  <i :class="getStatusIcon(donation.status)"></i>
                  {{ donation.status }}
                </span>
              </td>
              <td>
                <a :href="getTxLink(donation.txHash)" target="_blank" :title="donation.txHash">
                  {{ shortenHash(donation.txHash) }}
                  <i class="fas fa-external-link-alt"></i>
                </a>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <div class="empty-state" v-else>
        <i class="fas fa-donate"></i>
        <p>暂无捐赠记录</p>
        <button @click="goToDonate" class="btn btn-primary">
          <i class="fas fa-hand-holding-heart"></i> 去捐赠
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import Web3 from 'web3'
import { useRouter } from 'vue-router'

const router = useRouter()

const goHome = () => {
  router.push('/Home')
}

const goToDonate = () => {
  router.push('/donate')
}

const WalletType = {
  METAMASK: 'MetaMask',
  GANACHE: 'Ganache'
}

const GANACHE_CONFIG = {
  chainId: '0x7a69', 
  chainName: 'Ganache Local',
  rpcUrl: 'http://127.0.0.1:7545',
  blockExplorerUrl: '',
  nativeCurrency: {
    name: 'ETH',
    symbol: 'ETH',
    decimals: 18
  }
}

// 钱包状态
const walletConnected = ref(false)
const currentWallet = ref(null)
const walletAddress = ref('')
const ethBalance = ref('0')
const walletAvatar = ref('https://cdn.jsdelivr.net/gh/ethereum/meta-mask@master/logo.png')
const web3 = ref(null)
const connecting = ref(false)
const showCopiedFeedback = ref(false)
const refreshingBalance = ref(false)
const refreshingDonations = ref(false)
const sortBy = ref('date')
const sortAsc = ref(false)

// 捐赠历史数据（模拟数据）
const donations = ref([
  {
    date: new Date('2023-05-15T10:30:00'),
    amount: 0.5,
    project: '本地测试项目',
    status: '已完成',
    txHash: '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef'
  },
  {
    date: new Date('2023-06-20T14:45:00'),
    amount: 1.2,
    project: '慈善基金会',
    status: '已完成',
    txHash: '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890'
  },
  {
    date: new Date('2023-07-10T09:15:00'),
    amount: 0.3,
    project: '教育项目',
    status: '处理中',
    txHash: '0x7890abcdef1234567890abcdef1234567890abcdef1234567890abcdef123456'
  }
])

const connectWallet = async (walletType) => {
  try {
    connecting.value = true
    
    let provider
    
    if (walletType === WalletType.METAMASK) {
      if (!window.ethereum) throw new Error('请安装MetaMask')
      provider = window.ethereum
      
      // 请求账户访问
      const accounts = await provider.request({ method: 'eth_requestAccounts' })
      if (accounts.length === 0) throw new Error('没有检测到账户')
      
      web3.value = new Web3(provider)
      walletAddress.value = accounts[0]
      setupWalletListeners(provider)
    } else if (walletType === WalletType.GANACHE) {
      provider = new Web3.providers.HttpProvider(GANACHE_CONFIG.rpcUrl)
      web3.value = new Web3(provider)
      const accounts = await web3.value.eth.getAccounts()
      
      if (accounts.length === 0) throw new Error('Ganache中没有检测到账户')
      walletAddress.value = accounts[0]
    } else {
      throw new Error('不支持的钱包类型')
    }

    currentWallet.value = walletType
    walletConnected.value = true
    localStorage.setItem('preferredWallet', walletType) // 保存用户偏好
    
    await updateBalance(walletAddress.value)
    await fetchDonations() // 连接成功后获取捐赠记录
  } catch (error) {
    console.error('连接失败:', error)
    alert(`连接失败: ${error.message}`)
  } finally {
    connecting.value = false
  }
}

const updateBalance = async (address) => {
  try {
    refreshingBalance.value = true
    const balance = await web3.value.eth.getBalance(address)
    ethBalance.value = parseFloat(web3.value.utils.fromWei(balance, 'ether')).toFixed(4)
  } catch (error) {
    console.error('获取余额失败:', error)
    ethBalance.value = '0'
  } finally {
    refreshingBalance.value = false
  }
}

const refreshBalance = async () => {
  if (walletConnected.value) {
    await updateBalance(walletAddress.value)
  }
}

const fetchDonations = async () => {
  try {
    refreshingDonations.value = true
    // 这里应该是实际从区块链或后端API获取捐赠记录的逻辑
    // 目前使用模拟数据
    console.log('Fetching donations for address:', walletAddress.value)
  } catch (error) {
    console.error('获取捐赠记录失败:', error)
  } finally {
    refreshingDonations.value = false
  }
}

const refreshDonations = async () => {
  await fetchDonations()
}

const setupWalletListeners = (provider) => {
  if (currentWallet.value === WalletType.METAMASK) {
    provider.on('accountsChanged', handleAccountsChanged)
    provider.on('chainChanged', handleChainChanged)
  }
}

const removeWalletListeners = (provider) => {
  if (provider && currentWallet.value === WalletType.METAMASK) {
    provider.removeListener('accountsChanged', handleAccountsChanged)
    provider.removeListener('chainChanged', handleChainChanged)
  }
}

const handleAccountsChanged = (accounts) => {
  if (accounts.length === 0) {
    disconnectWallet()
  } else {
    walletAddress.value = accounts[0]
    updateBalance(accounts[0])
    fetchDonations() // 账户变更时重新获取捐赠记录
  }
}

const handleChainChanged = () => {
  window.location.reload()
}

const disconnectWallet = () => {
  const provider = getProvider()
  removeWalletListeners(provider)
  
  walletConnected.value = false
  walletAddress.value = ''
  currentWallet.value = null
  web3.value = null
  ethBalance.value = '0'
  donations.value = [] 
  
  localStorage.removeItem('preferredWallet')
}

const getProvider = () => {
  if (currentWallet.value === WalletType.METAMASK) {
    return window.ethereum
  } else if (currentWallet.value === WalletType.GANACHE) {
    return web3.value?.currentProvider
  }
  return null
}

const connectMetaMask = () => connectWallet(WalletType.METAMASK)
const connectGanache = () => connectWallet(WalletType.GANACHE)

const copyAddress = () => {
  navigator.clipboard.writeText(walletAddress.value)
  showCopiedFeedback.value = true
  setTimeout(() => {
    showCopiedFeedback.value = false
  }, 2000)
}

const formatDateTime = (date) => {
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date)
}

const shortenAddress = (address) => {
  if (!address) return ''
  return `${address.slice(0, 6)}...${address.slice(-4)}`
}

const shortenHash = (hash) => {
  if (!hash) return ''
  return `${hash.slice(0, 6)}...${hash.slice(-4)}`
}

const getTxLink = (txHash) => {
  if (currentWallet.value === WalletType.GANACHE) {
    return '#' // Ganache没有区块浏览器
  }
  return `https://etherscan.io/tx/${txHash}`
}

const getStatusIcon = (status) => {
  switch (status) {
    case '已完成':
      return 'fas fa-check-circle'
    case '处理中':
      return 'fas fa-spinner fa-pulse'
    default:
      return 'fas fa-info-circle'
  }
}

const sortDonations = (field) => {
  if (sortBy.value === field) {
    sortAsc.value = !sortAsc.value
  } else {
    sortBy.value = field
    sortAsc.value = true
  }
  
  donations.value.sort((a, b) => {
    let comparison = 0
    if (a[field] > b[field]) {
      comparison = 1
    } else if (a[field] < b[field]) {
      comparison = -1
    }
    return sortAsc.value ? comparison : -comparison
  })
}

// 自动连接上次使用的钱包
onMounted(async () => {
  const preferredWallet = localStorage.getItem('preferredWallet')
  
  if (preferredWallet === WalletType.METAMASK && window.ethereum) {
    try {
      const accounts = await window.ethereum.request({ method: 'eth_accounts' })
      if (accounts.length > 0) {
        await connectWallet(WalletType.METAMASK)
      }
    } catch (error) {
      console.log('自动连接MetaMask失败:', error)
    }
  } else if (preferredWallet === WalletType.GANACHE) {
    try {
      await connectWallet(WalletType.GANACHE)
    } catch (error) {
      console.log('自动连接Ganache失败:', error)
    }
  }
})

onBeforeUnmount(() => {
  const provider = getProvider()
  removeWalletListeners(provider)
})
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
@import url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css');

:root {
  --primary-color: #4361ee;
  --secondary-color: #3f37c9;
  --accent-color: #4cc9f0;
  --dark-color: #1a1a2e;
  --light-color: #f8f9fa;
  --success-color: #16db65;
  --error-color: #ff4d4f;
  --warning-color: #ffc107;
  --info-color: #17a2b8;
  --transition: all 0.3s ease;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Poppins', sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  min-height: 100vh;
  color: #333;
  overflow-x: hidden;
}

.profile-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.header h1 {
  font-size: 2.2rem;
  font-weight: 700;
  color: var(--primary-color);
  text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);
}

.user-nav {
  display: flex;
  gap: 15px;
}

.btn {
  padding: 10px 20px;
  border-radius: 30px;
  border: none;
  cursor: pointer;
  font-weight: 600;
  transition: var(--transition);
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 0.95rem;
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.btn-back {
  background-color: var(--primary-color);
  color: white;
}

.btn-back:hover:not(:disabled) {
  background-color: var(--secondary-color);
}

.btn-disconnect {
  background-color: var(--error-color);
  color: white;
}

.btn-disconnect:hover:not(:disabled) {
  background-color: #ff3333;
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: var(--secondary-color);
}

.btn-refresh {
  background-color: var(--light-color);
  color: var(--dark-color);
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.btn-refresh:hover:not(:disabled) {
  background-color: #e9ecef;
}

.wallet-info {
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
  margin-bottom: 40px;
  animation: fadeIn 0.5s ease;
}

.wallet-avatar {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.wallet-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 20px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  object-fit: contain;
}

.wallet-status {
  display: flex;
  align-items: center;
}

.status-indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 10px;
}

.connected {
  background-color: var(--success-color);
  box-shadow: 0 0 0 2px white, 0 0 0 4px var(--success-color);
  animation: pulse 2s infinite;
}

.wallet-details {
  padding: 20px;
  background: linear-gradient(135deg, rgba(67, 97, 238, 0.05) 0%, rgba(63, 55, 201, 0.05) 100%);
  border-radius: 15px;
}

.wallet-address {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  font-size: 1.1rem;
  font-family: 'Courier New', monospace;
  position: relative;
}

.copy-button {
  background: none;
  border: none;
  margin-left: 10px;
  cursor: pointer;
  color: var(--primary-color);
  transition: var(--transition);
}

.copy-button:hover {
  color: var(--secondary-color);
  transform: scale(1.1);
}

.copy-feedback {
  position: absolute;
  right: -80px;
  background: var(--dark-color);
  color: white;
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 0.8rem;
  opacity: 0;
  transition: var(--transition);
}

.copy-feedback.show {
  opacity: 1;
  right: -90px;
}

.wallet-balance {
  font-size: 1.2rem;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.refresh-button {
  background: none;
  border: none;
  cursor: pointer;
  color: var(--primary-color);
  transition: var(--transition);
}

.refresh-button:hover {
  color: var(--secondary-color);
  transform: rotate(360deg);
}

.connect-wallet {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  margin: 50px 0;
  flex-wrap: wrap;
}

.btn-metamask {
  background: linear-gradient(135deg, #f6851b, #e2761b);
  color: white;
}

.btn-metamask:hover:not(:disabled) {
  background: linear-gradient(135deg, #e2761b, #d16915);
}

.btn-ganache {
  background: linear-gradient(135deg, #4361ee, #3f37c9);
  color: white;
}

.btn-ganache:hover:not(:disabled) {
  background: linear-gradient(135deg, #3f37c9, #2a2590);
}

.wallet-tips {
  background-color: rgba(23, 162, 184, 0.1);
  padding: 15px;
  border-radius: 10px;
  color: var(--info-color);
  text-align: center;
  max-width: 500px;
  margin-top: 20px;
}

.wallet-tips i {
  margin-right: 8px;
}

.donation-history {
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.12);
  animation: fadeIn 0.7s ease;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.donation-history h2 {
  font-size: 1.8rem;
  color: var(--primary-color);
}

.history-table {
  overflow-x: auto;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

table {
  width: 100%;
  border-collapse: collapse;
  min-width: 600px;
}

th, td {
  padding: 15px 20px;
  text-align: left;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

th {
  background-color: rgba(67, 97, 238, 0.1);
  color: var(--dark-color);
  font-weight: 600;
  cursor: pointer;
  user-select: none;
}

th:hover {
  background-color: rgba(67, 97, 238, 0.2);
}

tr:hover {
  background-color: rgba(67, 97, 238, 0.03);
}

.status-已完成 {
  color: var(--success-color);
  font-weight: 600;
}

.status-处理中 {
  color: var(--warning-color);
  font-weight: 600;
}

.status-失败 {
  color: var(--error-color);
  font-weight: 600;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 20px;
  text-align: center;
}

.empty-state i {
  font-size: 3rem;
  color: var(--primary-color);
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 1.2rem;
  margin-bottom: 20px;
  color: var(--dark-color);
}

a {
  color: var(--primary-color);
  text-decoration: none;
  transition: var(--transition);
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

a:hover {
  color: var(--secondary-color);
  text-decoration: underline;
}

.fa-spin {
  animation: spin 1s infinite linear;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(22, 219, 101, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba(22, 219, 101, 0); }
  100% { box-shadow: 0 0 0 0 rgba(22, 219, 101, 0); }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .user-nav {
    width: 100%;
    justify-content: center;
  }
  
  .wallet-avatar {
    flex-direction: column;
    text-align: center;
  }
  
  .wallet-avatar img {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .connect-wallet {
    flex-direction: column;
    align-items: center;
  }
  
  .btn {
    width: 100%;
    max-width: 300px;
    justify-content: center;
  }
  
  .section-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .profile-page {
    padding: 20px 15px;
  }
  
  .wallet-info, .donation-history {
    padding: 20px;
  }
  
  th, td {
    padding: 12px 15px;
    font-size: 0.9rem;
  }
  
  .wallet-address {
    font-size: 0.9rem;
  }
  
  .wallet-balance {
    font-size: 1rem;
  }
}
</style>